package com.longrise.android.errorlog;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.http.util.EncodingUtils;

import com.longrise.android.Global;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;

public class UploadExceptionService extends Service implements Callback 
{
	private String appRootDir;
	private String path;
	private String res;
	private String content;
	private File[] files;
	private Handler handler;
	
	private static final int ACTION_START_UPLOAD = 0x100;
	private volatile int fileIndex = 0;

    private MyBinder myBinder = new MyBinder();
	
	@Override
	public IBinder onBind(Intent intent) 
	{
		return myBinder;
	}

	public void setAppRootDir(String appRootDir) {
		this.appRootDir = appRootDir;
	}
	
	@Override
	public void onCreate() 
	{
		super.onCreate();
		handler = new Handler(this);
	}


	@Override
	public void onDestroy() 
	{
		super.onDestroy();
	}
		
    /**
     * 根据文件名读取文件内容
     */
	private String readSDFile(String fileName)throws IOException
	{
		File file = new File(fileName);
		FileInputStream fis = new FileInputStream(path + file);
		int length = fis.available();
		byte[] buffer = new byte[length];
		fis.read(buffer);
		res = EncodingUtils.getString(buffer, "UTF-8");
		
		fis.close();
		return res;
	}
	
	/**
	 * 上传错误日志
	 */
	private void uploadError()   
	{
		try 
		{
			Boolean isUpload = (Boolean) Global.getInstance().call("lbcp_writeAppErrorLogs", Boolean.class, content);
			if(null != isUpload && isUpload)
			{
				if(fileIndex == files.length - 1)
				{
					files[fileIndex].delete();
					stopSelf();
				}
				else
				{
					files[fileIndex].delete();
					fileIndex ++;
					handler.sendEmptyMessage(ACTION_START_UPLOAD);
				}
			}
			else 
			{
				stopSelf();
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	private Runnable _do = new Runnable() 
	{
		@Override
		public void run() 
		{
			uploadError();
		}
	};
	

	@Override
	public boolean handleMessage(Message message) 
	{
		switch (message.what) 
		{
			case ACTION_START_UPLOAD:
				String fileName = files[fileIndex].getName();
				try 
				{
					content = readSDFile(fileName);
					Thread thread = new Thread(null, _do, "upload");
					thread.start();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
				break;
		}
		return false;
	}

	public class MyBinder extends Binder{
        
        public UploadExceptionService getService(){
            return UploadExceptionService.this;
        }
    }
}
